<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理系统 - 分类作品</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 新增分类作品视图样式 */
        .works-view {
            display: none;
        }

        .works-view .character-detail {
            background: rgba(255, 255, 255, 0.95);
        }

        .works-view .category-header {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid rgba(0,0,0,0.1);
        }

        .works-view .category-color-badge {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 15px;
            box-shadow: 0 3px 8px rgba(0,0,0,0.2);
        }

        .works-view .category-title {
            font-size: 28px;
            color: #333;
            margin: 0;
        }

        .works-view .best-works-count {
            color: #6c757d;
            font-size: 16px;
            margin-top: 5px;
            font-weight: 400;
        }

        .character-works-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
            margin-bottom: 25px;
        }

        .character-works-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }

        .character-header {
            padding: 18px;
            display: flex;
            align-items: center;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        .character-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 15px;
            object-fit: cover;
            background: linear-gradient(45deg, #f0f2f5, #e1e8ed);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            font-size: 22px;
        }

        .character-info {
            flex: 1;
        }

        .character-name {
            font-weight: 600;
            color: #333;
            font-size: 18px;
            margin-bottom: 3px;
        }

        .character-link {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.2s;
        }

        .character-link:hover {
            text-decoration: underline;
        }

        .work-items-container {
            padding: 0 20px 20px;
        }

        .work-item {
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .work-item:last-child {
            border-bottom: none;
        }

        .work-title {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }

        .work-title i {
            margin-right: 8px;
            color: #667eea;
        }

        .work-url {
            display: block;
            margin-bottom: 10px;
            color: #6c757d;
            word-break: break-all;
        }

        .work-url:hover {
            color: #667eea;
        }

        .work-meta {
            padding: 8px 12px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-top: 10px;
        }

        .work-meta-title {
            font-size: 12px;
            text-transform: uppercase;
            color: #6c757d;
            margin-bottom: 5px;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .work-categories {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .work-category-tag {
            background: #667eea;
            color: white;
            padding: 4px 12px;
            border-radius: 15px;
            font-size: 13px;
        }

        .no-results {
            text-align: center;
            padding: 40px;
            color: #6c757d;
            font-size: 18px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
        }

        .no-results-icon {
            font-size: 48px;
            color: #e9ecef;
            margin-bottom: 15px;
        }

        .no-results h3 {
            color: #495057;
            margin-bottom: 10px;
        }

        /* 原有样式 */
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .header-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }

        .add-btn, .category-btn {
            background: linear-gradient(45deg, #ff6b6b, #ee5a52);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(255,107,107,0.3);
            transition: all 0.3s ease;
        }

        .category-btn {
            background: linear-gradient(45deg, #4ecdc4, #44a08d);
            box-shadow: 0 4px 15px rgba(78,205,196,0.3);
        }

        .add-btn:hover, .category-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255,107,107,0.4);
        }

        .category-btn:hover {
            box-shadow: 0 6px 20px rgba(78,205,196,0.4);
        }

        .filters-section {
            background: rgba(255,255,255,0.1);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .search-bar {
            width: 100%;
            max-width: 400px;
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            margin-bottom: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .category-filters {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
            justify-content: center;
        }

        .category-tag {
            background: rgba(255,255,255,0.2);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            border: 2px solid transparent;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .category-tag:hover {
            background: rgba(255,255,255,0.3);
        }

        .category-tag.active {
            background: white;
            color: #667eea;
            border-color: white;
        }

        .cards-container {
            column-count: 3;
            column-gap: 20px;
            margin-bottom: 50px;
        }

        @media (max-width: 1024px) {
            .cards-container {
                column-count: 2;
            }
        }

        @media (max-width: 640px) {
            .cards-container {
                column-count: 1;
            }
        }

        .character-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
            animation: slideUp 0.6s ease forwards;
            opacity: 0;
            transform: translateY(30px);
            break-inside: avoid;
            margin-bottom: 20px;
            position: relative;
        }

        @keyframes slideUp {
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .character-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.15);
        }

        .card-image {
            width: 100%;
            height: auto;
            min-height: 200px;
            max-height: 400px;
            object-fit: cover;
            background: linear-gradient(45deg, #f0f2f5, #e1e8ed);
            display: block;
        }

        .card-image.placeholder {
            height: 250px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            font-size: 48px;
        }

        .card-content {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: linear-gradient(transparent, rgba(0,0,0,0.8));
            padding: 40px 20px 20px;
            color: white;
        }

        .card-name {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 8px;
            color: white;
            text-shadow: 0 2px 4px rgba(0,0,0,0.5);
        }

        .card-actions {
            display: flex;
            gap: 8px;
            margin-top: 15px;
        }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .edit-btn {
            background: rgba(52, 152, 219, 0.8);
            color: white;
        }

        .delete-btn {
            background: rgba(231, 76, 60, 0.8);
            color: white;
        }

        .btn:hover {
            transform: scale(1.05);
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                transform: scale(0.8);
                opacity: 0;
            }
            to {
                transform: scale(1);
                opacity: 1;
            }
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e8ed;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .url-list {
            margin-top: 10px;
        }

        .url-item {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 15px;
            padding: 15px;
            border: 1px solid #e1e8ed;
            border-radius: 10px;
            background: #f8f9fa;
        }

        .url-input-row {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .url-input {
            flex: 1;
        }

        .work-categories {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }

        .category-checkbox {
            display: flex;
            align-items: center;
            gap: 5px;
            background: white;
            padding: 5px 10px;
            border-radius: 15px;
            border: 1px solid #ddd;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .category-checkbox:hover {
            background: #f0f7ff;
            border-color: #667eea;
        }

        .category-checkbox.selected {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .category-checkbox input {
            display: none;
        }

        .remove-url {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
        }

        .add-url {
            background: #27ae60;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }

        .modal-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
        }

        .save-btn {
            background: linear-gradient(45deg, #27ae60, #2ecc71);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
        }

        .cancel-btn {
            background: #95a5a6;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
        }

        .category-management {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .category-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            margin-bottom: 10px;
            background: #f8f9fa;
        }

        .category-name {
            font-weight: 500;
            color: #2c3e50;
        }

        .category-color {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .category-info {
            display: flex;
            align-items: center;
        }

        .category-actions {
            display: flex;
            gap: 8px;
        }

        .detail-view {
            display: none;
        }

        .detail-header {
            display: flex;
            align-items: center;
            margin-bottom: 30px;
        }

        .back-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            cursor: pointer;
            margin-right: 20px;
        }

        .character-detail {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .detail-image {
            width: 200px;
            height: 200px;
            object-fit: cover;
            border-radius: 15px;
            float: left;
            margin-right: 30px;
            margin-bottom: 20px;
            background: linear-gradient(45deg, #f0f2f5, #e1e8ed);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            font-size: 72px;
        }

        .detail-info h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 2rem;
        }

        .works-section {
            clear: both;
            margin-top: 30px;
        }

        .works-section h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 1.3rem;
        }

        .works-list {
            list-style: none;
            padding: 0;
        }

        .works-list li {
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 12px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .work-link {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
            display: block;
            margin-bottom: 8px;
        }

        .work-link:hover {
            text-decoration: underline;
        }

        .work-categories-detail {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }

        .work-category-tag {
            background: #667eea;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: white;
            font-size: 18px;
        }

        .color-picker {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            flex-wrap: wrap;
        }

        .color-option {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            cursor: pointer;
            border: 3px solid transparent;
            transition: border-color 0.3s ease;
        }

        .color-option.selected {
            border-color: #333;
        }

        .filter-info {
            text-align: center;
            color: white;
            margin-top: 10px;
            font-style: italic;
            font-size: 0.9rem;
        }

        @media (max-width: 768px) {
            .detail-image {
                float: none;
                width: 100%;
                height: 250px;
                margin-right: 0;
                margin-bottom: 20px;
            }

            .header-actions {
                flex-direction: column;
                align-items: center;
            }

            .category-filters {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 主页面 -->
    <div id="mainView">
        <div class="header">
            <h1>🎭 角色管理系统</h1>
            <div class="header-actions">
                <button class="add-btn" onclick="openModal()"><i class="fas fa-plus"></i> 添加角色</button>
                <button class="category-btn" onclick="openCategoryModal()"><i class="fas fa-tags"></i> 管理分类</button>
            </div>
        </div>

        <div class="filters-section">
            <input type="text" class="search-bar" id="searchInput" placeholder="搜索角色名称..." onkeyup="searchCharacters()">
            <div class="category-filters" id="categoryFilters">
                <!-- 分类筛选标签将在这里动态生成 -->
            </div>
            <div class="filter-info">点击分类查看该分类下的所有作品（按角色分组）</div>
        </div>

        <div class="cards-container" id="cardsContainer">
            <!-- 角色卡片将在这里动态生成 -->
        </div>

        <div class="loading" id="loading" style="display: none;">
            正在加载更多...
        </div>
    </div>

    <!-- 详情页面 -->
    <div id="detailView" class="detail-view">
        <div class="detail-header">
            <button class="back-btn" onclick="showMainView()"><i class="fas fa-arrow-left"></i> 返回</button>
            <h2 style="color: white;">角色详情</h2>
        </div>
        <div class="character-detail" id="characterDetail">
            <!-- 详情内容将在这里动态生成 -->
        </div>
    </div>

    <!-- 新增：分类作品列表视图 -->
    <div id="worksView" class="works-view">
        <div class="detail-header">
            <button class="back-btn" onclick="showMainView()"><i class="fas fa-arrow-left"></i> 返回</button>
            <h2 style="color: white;">分类作品列表</h2>
        </div>
        <div class="character-detail">
            <div class="category-header">
                <div class="category-color-badge" id="worksCategoryColor"></div>
                <div>
                    <h2 class="category-title" id="worksCategoryTitle"></h2>
                    <div class="best-works-count" id="bestWorksCount"></div>
                </div>
            </div>
            <div id="groupedWorksContainer">
                <!-- 分组后的作品列表将在这里动态生成 -->
            </div>
        </div>
    </div>
</div>

<!-- 角色模态框 -->
<div class="modal" id="modal">
    <div class="modal-content">
        <h2 id="modalTitle">添加角色</h2>
        <form id="characterForm">
            <div class="form-group">
                <label for="name">角色名称</label>
                <input type="text" id="name" required>
            </div>

            <div class="form-group">
                <label for="image">角色图片URL</label>
                <input type="url" id="image" placeholder="https://example.com/image.jpg">
            </div>

            <div class="form-group">
                <label>最佳作品列表</label>
                <div id="bestWorksList" class="url-list">
                    <!-- 最佳作品项将在这里动态生成 -->
                </div>
                <button type="button" class="add-url" onclick="addBestWorkField()">+ 添加最佳作品</button>
            </div>

            <div class="form-group">
                <label>作品列表</label>
                <div id="worksList" class="url-list">
                    <div class="url-item">
                        <div class="url-input-row">
                            <input type="url" class="url-input" placeholder="https://example.com/work1">
                            <button type="button" class="remove-url" onclick="removeUrlField(this)">删除</button>
                        </div>
                    </div>
                </div>
                <button type="button" class="add-url" onclick="addUrlField('worksList')">+ 添加作品</button>
            </div>

            <div class="modal-actions">
                <button type="button" class="cancel-btn" onclick="closeModal()">取消</button>
                <button type="submit" class="save-btn">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 分类管理模态框 -->
<div class="modal" id="categoryModal">
    <div class="modal-content">
        <h2>分类管理</h2>

        <div class="form-group">
            <label>添加新分类</label>
            <div style="display: flex; gap: 10px; align-items: flex-end;">
                <div style="flex: 1;">
                    <input type="text" id="newCategoryName" placeholder="分类名称">
                </div>
                <button type="button" class="add-url" onclick="addCategory()">添加</button>
            </div>
            <div class="color-picker" id="colorPicker">
                <div class="color-option selected" style="background: #667eea" data-color="#667eea"></div>
                <div class="color-option" style="background: #ff6b6b" data-color="#ff6b6b"></div>
                <div class="color-option" style="background: #4ecdc4" data-color="#4ecdc4"></div>
                <div class="color-option" style="background: #45b7d1" data-color="#45b7d1"></div>
                <div class="color-option" style="background: #96ceb4" data-color="#96ceb4"></div>
                <div class="color-option" style="background: #feca57" data-color="#feca57"></div>
                <div class="color-option" style="background: #ff9ff3" data-color="#ff9ff3"></div>
                <div class="color-option" style="background: #a29bfe" data-color="#a29bfe"></div>
            </div>
        </div>

        <div class="category-management">
            <h3>现有分类</h3>
            <div id="categoryList">
                <!-- 分类列表将在这里动态生成 -->
            </div>
        </div>

        <div class="modal-actions">
            <button type="button" class="cancel-btn" onclick="closeCategoryModal()">关闭</button>
        </div>
    </div>
</div>

<script>
    let characters = [];
    let categories = [];
    let currentPage = 1;
    const itemsPerPage = 12;
    let filteredCharacters = [];
    let editingId = null;
    let selectedCategories = [];
    let currentCategory = null;

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadCategories();
        loadCharacters();
        setupInfiniteScroll();
        setupColorPicker();
    });

    // 本地存储操作
    function saveToStorage() {
        localStorage.setItem('characters', JSON.stringify(characters));
        localStorage.setItem('categories', JSON.stringify(categories));
    }

    function loadFromStorage() {
        const storedCharacters = localStorage.getItem('characters');
        const storedCategories = localStorage.getItem('categories');

        return {
            characters: storedCharacters ? JSON.parse(storedCharacters) : [],
            categories: storedCategories ? JSON.parse(storedCategories) : []
        };
    }

    // 加载分类数据
    function loadCategories() {
        const stored = loadFromStorage();
        categories = stored.categories;

        if (categories.length === 0) {
            // 添加默认分类
            categories = [
                { id: 1, name: '武侠', color: '#667eea' },
                { id: 2, name: '神话', color: '#ff6b6b' },
                { id: 3, name: '历史', color: '#4ecdc4' },
                { id: 4, name: '民间传说', color: '#45b7d1' },
                { id: 5, name: '古典文学', color: '#96ceb4' }
            ];
            saveToStorage();
        }

        renderCategoryFilters();
        renderCategoryList();
    }

    // 加载角色数据
    function loadCharacters() {
        const stored = loadFromStorage();
        characters = stored.characters;

        if (characters.length === 0) {
            // 添加示例数据
            characters = [
                {
                    id: 1,
                    name: "孙悟空",
                    image: "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400&h=600&fit=crop",
                    bestWorks: [
                        { url: "https://example.com/journey-to-west", title: "西游记", categories: [1, 2] },
                        { url: "https://example.com/monkey-king", title: "大闹天宫", categories: [2] }
                    ],
                    works: ["https://example.com/work1", "https://example.com/work2", "https://example.com/work3"]
                },
                {
                    id: 2,
                    name: "白娘子",
                    image: "https://images.unsplash.com/photo-1544005313-94ddf0286df2?w=400&h=500&fit=crop",
                    bestWorks: [
                        { url: "https://example.com/white-snake", title: "白蛇传", categories: [2, 4] },
                        { url: "https://example.com/white-snake2", title: "白娘子传奇", categories: [2] }
                    ],
                    works: ["https://example.com/legend1", "https://example.com/legend2"]
                },
                {
                    id: 3,
                    name: "花木兰",
                    image: "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=400&h=700&fit=crop",
                    bestWorks: [
                        { url: "https://example.com/mulan-ballad", title: "木兰诗", categories: [3, 4] }
                    ],
                    works: ["https://example.com/warrior1", "https://example.com/warrior2", "https://example.com/warrior3"]
                },
                {
                    id: 4,
                    name: "诸葛亮",
                    image: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=550&fit=crop",
                    bestWorks: [
                        { url: "https://example.com/three-kingdoms", title: "三国演义", categories: [3, 5] },
                        { url: "https://example.com/three-kingdoms2", title: "出师表", categories: [5] }
                    ],
                    works: ["https://example.com/strategy1", "https://example.com/strategy2"]
                },
                {
                    id: 5,
                    name: "嫦娥",
                    image: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=400&h=650&fit=crop",
                    bestWorks: [
                        { url: "https://example.com/moon-goddess", title: "嫦娥奔月", categories: [2, 4] }
                    ],
                    works: ["https://example.com/moon1", "https://example.com/moon2", "https://example.com/moon3", "https://example.com/moon4"]
                }
            ];
            saveToStorage();
        }
        filteredCharacters = [...characters];
        displayCharacters();
    }

    // 渲染分类筛选器
    function renderCategoryFilters() {
        const container = document.getElementById('categoryFilters');
        const allTag = document.createElement('div');
        allTag.className = 'category-tag active';
        allTag.textContent = '全部';
        allTag.onclick = () => {
            showMainView();
        };
        container.innerHTML = '';
        container.appendChild(allTag);

        categories.forEach(category => {
            const tag = document.createElement('div');
            tag.className = 'category-tag';
            tag.textContent = category.name;
            tag.style.borderColor = category.color;
            tag.onclick = () => showWorksByCategory(category.id);
            container.appendChild(tag);
        });
    }

    // 渲染分类列表
    function renderCategoryList() {
        const container = document.getElementById('categoryList');
        container.innerHTML = '';

        categories.forEach(category => {
            const item = document.createElement('div');
            item.className = 'category-item';
            item.innerHTML = `
                <div class="category-info">
                    <div class="category-color" style="background: ${category.color}"></div>
                    <span class="category-name">${category.name}</span>
                </div>
                <div class="category-actions">
                    <button class="btn edit-btn" onclick="editCategory(${category.id})">编辑</button>
                    <button class="btn delete-btn" onclick="deleteCategory(${category.id})">删除</button>
                </div>
            `;
            container.appendChild(item);
        });
    }

    // 显示某个分类下的作品（按角色分组）
    function showWorksByCategory(categoryId) {
        const category = categories.find(c => c.id === categoryId);
        if (!category) return;

        currentCategory = category;

        // 更新UI显示
        document.getElementById('worksCategoryTitle').textContent = category.name;
        document.getElementById('worksCategoryColor').style.background = category.color;

        // 获取该分类下的所有作品（按角色分组）
        const groupedWorks = {};
        let totalWorks = 0;

        characters.forEach(character => {
            if (!character.bestWorks) return;

            character.bestWorks.forEach(work => {
                if (work.categories && work.categories.includes(categoryId)) {
                    if (!groupedWorks[character.id]) {
                        groupedWorks[character.id] = {
                            character: character,
                            works: []   // 该角色在当前分类下的作品列表
                        };
                    }
                    groupedWorks[character.id].works.push(work);
                    totalWorks++;
                }
            });
        });

        // 更新作品数量
        const characterCount = Object.keys(groupedWorks).length;
        document.getElementById('bestWorksCount').textContent =
            `共收录了 ${characterCount} 个角色的 ${totalWorks} 部作品`;

        // 渲染分组后的作品列表
        const worksContainer = document.getElementById('groupedWorksContainer');

        if (characterCount === 0) {
            worksContainer.innerHTML = `
                <div class="no-results">
                    <div class="no-results-icon"><i class="fas fa-box-open"></i></div>
                    <h3>没有找到相关作品</h3>
                    <p>该分类下暂时没有添加作品</p>
                </div>
            `;
        } else {
            worksContainer.innerHTML = '';

            Object.values(groupedWorks).forEach(group => {
                const character = group.character;
                const works = group.works;

                const characterCard = document.createElement('div');
                characterCard.className = 'character-works-card';

                // 构建角色头像
                const avatarElement = character.image
                    ? `<img src="${character.image}" class="character-avatar" alt="${character.name}">`
                    : `<div class="character-avatar">${character.name.charAt(0)}</div>`;

                // 构建作品列表
                let worksHTML = '';

                works.forEach(work => {
                    // 构建分类标签
                    let categoryTags = '';
                    if (work.categories && work.categories.length > 0) {
                        work.categories.forEach(catId => {
                            const cat = categories.find(c => c.id === catId);
                            if (cat) {
                                categoryTags += `<div class="work-category-tag" style="background: ${cat.color}">${cat.name}</div>`;
                            }
                        });
                    }

                    const workTitle = work.title || work.url;

                    worksHTML += `
                        <div class="work-item">
                            <div class="work-title"><i class="fas fa-star"></i> ${workTitle}</div>
                            <a href="${work.url}" target="_blank" class="work-url">${work.url}</a>
                            <div class="work-meta">
                                <div class="work-meta-title">作品分类</div>
                                <div class="work-categories">${categoryTags}</div>
                            </div>
                        </div>
                    `;
                });

                characterCard.innerHTML = `
                    <div class="character-header">
                        ${avatarElement}
                        <div class="character-info">
                            <div class="character-name">${character.name}</div>
                            <a href="javascript:void(0)" class="character-link" onclick="showCharacterDetail(${character.id})">
                                查看角色详情 <i class="fas fa-chevron-right"></i>
                            </a>
                        </div>
                    </div>
                    <div class="work-items-container">
                        ${worksHTML}
                    </div>
                `;

                worksContainer.appendChild(characterCard);
            });
        }

        // 切换视图
        document.getElementById('mainView').style.display = 'none';
        document.getElementById('detailView').style.display = 'none';
        document.getElementById('worksView').style.display = 'block';
    }

    // 显示角色卡片
    function displayCharacters() {
        const container = document.getElementById('cardsContainer');
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const charactersToShow = filteredCharacters.slice(startIndex, endIndex);

        if (currentPage === 1) {
            container.innerHTML = '';
        }

        charactersToShow.forEach((character, index) => {
            const card = createCharacterCard(character);
            card.style.animationDelay = `${index * 0.1}s`;
            container.appendChild(card);
        });

        // 检查是否还有更多数据
        if (endIndex >= filteredCharacters.length) {
            document.getElementById('loading').style.display = 'none';
        }
    }

    // 创建角色卡片
    function createCharacterCard(character) {
        const card = document.createElement('div');
        card.className = 'character-card';
        card.onclick = () => showCharacterDetail(character.id);

        if (character.image) {
            card.innerHTML = `
                <img src="${character.image}" alt="${character.name}" class="card-image"
                     onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                <div class="card-image placeholder" style="display:none;">${character.name.charAt(0)}</div>
                <div class="card-content">
                    <div class="card-name">${character.name}</div>
                    <div class="card-actions">
                        <button class="btn edit-btn" onclick="event.stopPropagation(); editCharacter(${character.id})">编辑</button>
                        <button class="btn delete-btn" onclick="event.stopPropagation(); deleteCharacter(${character.id})">删除</button>
                    </div>
                </div>
            `;
        } else {
            card.innerHTML = `
                <div class="card-image placeholder">${character.name.charAt(0)}</div>
                <div class="card-content">
                    <div class="card-name">${character.name}</div>
                    <div class="card-actions">
                        <button class="btn edit-btn" onclick="event.stopPropagation(); editCharacter(${character.id})">编辑</button>
                        <button class="btn delete-btn" onclick="event.stopPropagation(); deleteCharacter(${character.id})">删除</button>
                    </div>
                </div>
            `;
        }

        return card;
    }

    // 搜索功能
    function searchCharacters() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        filteredCharacters = characters.filter(character =>
            character.name.toLowerCase().includes(searchTerm)
        );
        currentPage = 1;
        displayCharacters();
    }

    // 无限滚动
    function setupInfiniteScroll() {
        let loading = false;

        window.addEventListener('scroll', () => {
            if (loading) return;

            const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

            if (scrollTop + clientHeight >= scrollHeight - 500) {
                loading = true;
                document.getElementById('loading').style.display = 'block';

                setTimeout(() => {
                    currentPage++;
                    displayCharacters();
                    loading = false;
                }, 800);
            }
        });
    }

    // 颜色选择器设置
    function setupColorPicker() {
        document.querySelectorAll('.color-option').forEach(option => {
            option.addEventListener('click', function() {
                document.querySelectorAll('.color-option').forEach(opt => opt.classList.remove('selected'));
                this.classList.add('selected');
            });
        });
    }

    // 分类管理
    function openCategoryModal() {
        document.getElementById('categoryModal').style.display = 'flex';
        renderCategoryList();
    }

    function closeCategoryModal() {
        document.getElementById('categoryModal').style.display = 'none';
        document.getElementById('newCategoryName').value = '';
    }

    function addCategory() {
        const name = document.getElementById('newCategoryName').value.trim();
        if (!name) {
            alert('请输入分类名称');
            return;
        }

        if (categories.some(cat => cat.name === name)) {
            alert('分类名已存在');
            return;
        }

        const selectedColor = document.querySelector('.color-option.selected').dataset.color;
        const newCategory = {
            id: Date.now(),
            name: name,
            color: selectedColor
        };

        categories.push(newCategory);
        saveToStorage();
        renderCategoryList();
        renderCategoryFilters();
        document.getElementById('newCategoryName').value = '';
    }

    function editCategory(id) {
        const category = categories.find(c => c.id === id);
        if (!category) return;

        const newName = prompt('修改分类名称:', category.name);
        if (newName && newName.trim() !== '') {
            category.name = newName.trim();
            saveToStorage();
            renderCategoryList();
            renderCategoryFilters();
        }
    }

    function deleteCategory(id) {
        if (confirm('确定要删除这个分类吗？删除后相关的作品分类关联也会被移除。')) {
            categories = categories.filter(c => c.id !== id);

            // 从所有角色的作品中移除此分类
            characters.forEach(character => {
                character.bestWorks.forEach(work => {
                    if (work.categories) {
                        work.categories = work.categories.filter(catId => catId !== id);
                    }
                });
            });

            saveToStorage();
            renderCategoryList();
            renderCategoryFilters();
            loadCharacters(); // 重新加载角色以更新显示

            // 如果当前在查看该分类的作品，返回到主视图
            if (currentCategory && currentCategory.id === id) {
                showMainView();
            }
        }
    }

    // 角色模态框操作
    function openModal(character = null) {
        const modal = document.getElementById('modal');
        const form = document.getElementById('characterForm');
        const title = document.getElementById('modalTitle');

        if (character) {
            title.textContent = '编辑角色';
            editingId = character.id;
            fillForm(character);
        } else {
            title.textContent = '添加角色';
            editingId = null;
            form.reset();
            resetUrlLists();
        }

        modal.style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('modal').style.display = 'none';
    }

    function fillForm(character) {
        document.getElementById('name').value = character.name;
        document.getElementById('image').value = character.image || '';

        // 填充最佳作品列表
        const bestWorksList = document.getElementById('bestWorksList');
        bestWorksList.innerHTML = '';
        character.bestWorks.forEach(work => {
            addBestWorkField(work.url, work.categories || [], work.title);
        });

        // 填充作品列表
        const worksList = document.getElementById('worksList');
        worksList.innerHTML = '';
        character.works.forEach(work => {
            addUrlField('worksList', work);
        });
    }

    function resetUrlLists() {
        document.getElementById('bestWorksList').innerHTML = '';
        addBestWorkField();

        document.getElementById('worksList').innerHTML = `
            <div class="url-item">
                <div class="url-input-row">
                    <input type="url" class="url-input" placeholder="https://example.com/work1">
                    <button type="button" class="remove-url" onclick="removeUrlField(this)">删除</button>
                </div>
            </div>
        `;
    }

    // 最佳作品字段操作
    function addBestWorkField(url = '', selectedCategories = [], title = '') {
        const list = document.getElementById('bestWorksList');
        const urlItem = document.createElement('div');
        urlItem.className = 'url-item';

        const categoryCheckboxes = categories.map(category => `
            <label class="category-checkbox ${selectedCategories.includes(category.id) ? 'selected' : ''}"
                   style="border-color: ${category.color}">
                <input type="checkbox" value="${category.id}"
                       ${selectedCategories.includes(category.id) ? 'checked' : ''}>
                <span>${category.name}</span>
            </label>
        `).join('');

        urlItem.innerHTML = `
            <div class="url-input-row">
                <input type="text" class="url-input" placeholder="作品名称" value="${title}" style="flex: 0.6;">
                <input type="url" class="url-input" placeholder="https://example.com/best-work" value="${url}" style="flex: 1;">
                <button type="button" class="remove-url" onclick="removeUrlField(this)">删除</button>
            </div>
            <div class="work-categories">
                ${categoryCheckboxes}
            </div>
        `;

        // 添加分类选择事件
        urlItem.querySelectorAll('.category-checkbox').forEach(checkbox => {
            checkbox.addEventListener('click', function() {
                const input = this.querySelector('input');
                input.checked = !input.checked;
                this.classList.toggle('selected', input.checked);
            });
        });

        list.appendChild(urlItem);
    }

    // URL字段操作
    function addUrlField(listId, value = '') {
        const list = document.getElementById(listId);
        const urlItem = document.createElement('div');
        urlItem.className = 'url-item';
        urlItem.innerHTML = `
            <div class="url-input-row">
                <input type="url" class="url-input" placeholder="https://example.com/work" value="${value}">
                <button type="button" class="remove-url" onclick="removeUrlField(this)">删除</button>
            </div>
        `;
        list.appendChild(urlItem);
    }

    function removeUrlField(button) {
        button.closest('.url-item').remove();
    }

    // 表单提交
    document.getElementById('characterForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const name = document.getElementById('name').value;
        const image = document.getElementById('image').value;

        // 处理最佳作品
        const bestWorks = Array.from(document.querySelectorAll('#bestWorksList .url-item')).map(item => {
            const urlInput = item.querySelectorAll('.url-input');
            const url = urlInput[1].value.trim();
            const title = urlInput[0].value.trim() || url; // 如果没有标题，使用URL
            const categories = Array.from(item.querySelectorAll('.category-checkbox input:checked'))
                .map(input => parseInt(input.value));
            return url ? { url, categories, title } : null;
        }).filter(work => work !== null);

        // 处理普通作品
        const works = Array.from(document.querySelectorAll('#worksList .url-input'))
            .map(input => input.value.trim())
            .filter(url => url !== '');

        const character = {
            id: editingId || Date.now(),
            name,
            image,
            bestWorks,
            works
        };

        if (editingId) {
            const index = characters.findIndex(c => c.id === editingId);
            characters[index] = character;
        } else {
            characters.push(character);
        }

        saveToStorage();
        loadCharacters();
        closeModal();
    });

    // CRUD操作
    function editCharacter(id) {
        const character = characters.find(c => c.id === id);
        openModal(character);
    }

    function deleteCharacter(id) {
        if (confirm('确定要删除这个角色吗？')) {
            characters = characters.filter(c => c.id !== id);
            saveToStorage();
            loadCharacters();
        }
    }

    // 显示角色详情
    function showCharacterDetail(id) {
        const character = characters.find(c => c.id === id);
        if (!character) return;

        const detailContainer = document.getElementById('characterDetail');
        const imageElement = character.image
            ? `<img src="${character.image}" alt="${character.name}" class="detail-image" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
               <div class="detail-image" style="display:none;">${character.name.charAt(0)}</div>`
            : `<div class="detail-image">${character.name.charAt(0)}</div>`;

        const bestWorksHtml = character.bestWorks.map(work => {
            const workCategories = work.categories ? work.categories.map(catId => {
                const category = categories.find(c => c.id === catId);
                return category ? `<span class="work-category-tag" style="background: ${category.color}">${category.name}</span>` : '';
            }).join('') : '';

            return `
                <li>
                    <div class="work-link">
                        <strong>${work.title || work.url}</strong>
                        <a href="${work.url}" target="_blank" class="work-url">${work.url}</a>
                    </div>
                    <div class="work-categories-detail">${workCategories}</div>
                </li>
            `;
        }).join('');

        const worksHtml = character.works.map(work => `
            <li><a href="${work}" target="_blank" class="work-link">${work}</a></li>
        `).join('');

        detailContainer.innerHTML = `
            ${imageElement}
            <div class="detail-info">
                <h2>${character.name}</h2>

                <div class="works-section">
                    <h3>🏆 最佳作品</h3>
                    <ul class="works-list">
                        ${bestWorksHtml}
                    </ul>
                </div>

                <div class="works-section">
                    <h3>📚 作品列表</h3>
                    <ul class="works-list">
                        ${worksHtml}
                    </ul>
                </div>
            </div>
        `;

        document.getElementById('mainView').style.display = 'none';
        document.getElementById('detailView').style.display = 'block';
        document.getElementById('worksView').style.display = 'none';
    }

    // 显示主视图
    function showMainView() {
        document.getElementById('mainView').style.display = 'block';
        document.getElementById('detailView').style.display = 'none';
        document.getElementById('worksView').style.display = 'none';
        currentCategory = null;

        // 重置筛选标签
        document.querySelectorAll('.category-tag').forEach(tag => {
            tag.classList.remove('active');
        });
        document.querySelector('.category-tag').classList.add('active');
    }

    // 点击模态框外部关闭
    document.getElementById('modal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal();
        }
    });

    document.getElementById('categoryModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeCategoryModal();
        }
    });
</script>
</body>
</html>